

//当前修改的行
var editingId;
function formatProgress(value){
	if (value) {
		var s = '<div style="width:100%;border:1px solid #ccc">'
				+ '<div style="width:' + value
				+ '%;background:#cc0000;color:#fff">' + value + '%' + '</div>'
				+ '</div>';
		return s;
	} else {
		return '';
	}
}

function remove(){
	if(editingId){
		$('#tg').treegrid("remove",editingId);
		editingId=undefined ;
	}
}


function save(){
	var tg = $('#tg');
	var pgd = $("#pgd");
	if (editingId){
		tg.treegrid('acceptChanges', editingId);
		var arrRow = pgd.propertygrid("getRows");
		if(tg.treegrid('getSelected', editingId)['type']){
			tg.treegrid("find",editingId).options=JSON.stringify(arrRow) ;
		}
		tg.treegrid('endEdit', editingId);
		//tg.treegrid('unselect', editingId);
		editingId = undefined;
	}
	pgd.propertygrid("loadData",[]);
}

function cancel(){		
	var tg = $('#tg');
	var row = tg.treegrid('getSelected');
	if (row){
		tg.treegrid('cancelEdit', row.id);
		editingId = undefined;
	}
}

	
function append(){
	save();
	var obj = $('#tg') ;
	var row = obj.treegrid('getSelected');
	obj.treegrid("append",{
			parent:row['id'] ,
			data:[{
				id:new UUID().id,
				field:""
			}]
	})	;
}

function clickAction(rowData){
	$(this).treegrid("select",rowData['id']) ;
}

function dblClickAction(rowData){
	var tg = $(this) ;
	try{
		save();
		editingId = rowData.id ;
		tg.treegrid('beginEdit',
								editingId);
		var arrEditor = tg.treegrid("getEditors",editingId) ;
		jQuery.each(arrEditor,function(index,editor){
			var target = $(editor.target) ;
			
			bindListener(editor,rowData) ;
			if (editor.type=="combobox") {
				if(rowData){
					if(rowData['type']){
						loadPropGrid(rowData['type'],rowData['options']);
					}
					var rowParent = tg.treegrid("getParent",rowData['id']) ;
					if(rowParent){
						if(rowParent['type']=="fieldset"||rowParent['type']=="table"){
							target.combobox("reload","formType.json");
						}else if(rowParent['type']=="datagrid"){
							//alert(target.combobox("options")['width']);
							target.combobox("options").panelHeight='auto';
							target.combobox("reload","datagridType.json");
							//alert(target.combobox("options")['width']);
						}else{
							target.combobox("reload","controlType.json");
						}
					}else{
						target.combobox("reload","controlType.json");
					}
				}else{
					$.messager.alert('Warning','!');   
				}
			}
		});
	}catch(e){
		console.log(e);
		$.messager.alert("error",e);
	}
}

function loadCtrlData(key,value,rowData){
	if(key=="type"){
		loadPropGrid(value,rowData['options']);
	}
}

function loadPropGrid(key,options){
	var pgd = $("#pgd") ;
	var tmpOpt = (options==undefined?options:JSON.parse(options) );
	if(tmpOpt){
		//$("#pgd").propertygrid("loadData",JSON.parse('[{"name":"name","value":"huangyw","editor":"text","group":"properties","datatype":"string"}]'));
		pgd.propertygrid("loadData",tmpOpt);
		return ;
	}
	if(key=="combobox"){
		pgd.propertygrid({url:'../treegrid/combobox_prop.json'});
	}else if (key=="combo") {
		pgd.propertygrid({url:'../treegrid/combo.json'});
	}else if (key=="validatebox") {
		pgd.propertygrid({url:'../treegrid/validatebox.json'});
	}else if (key=="calendar") {
		pgd.propertygrid({url:'../treegrid/calendar.json'});
	}else if (key=="datebox") {
		pgd.propertygrid({url:'../treegrid/datebox.json'});
	}else if (key=="numberbox") {
		pgd.propertygrid({url:'../treegrid/numberbox.json'});
	}else if (key=="tabs") {
		pgd.propertygrid({url:'../treegrid/tabs.json'});
	}else if (key=="layout") {
		pgd.propertygrid({url:'../treegrid/layout.json'});
	}else if (key=="region") {
		pgd.propertygrid({url:'../treegrid/region.json'});
	}else if (key=="datagrid") {
		pgd.propertygrid({url:'../treegrid/datagrid.json'});
	}else if (key=="column") {
		pgd.propertygrid({url:'../treegrid/column.json'});
	}else if (key=="pagination") {
		pgd.propertygrid({url:'../treegrid/pagination.json'});
	}else if (key=="searchbox") {
		pgd.propertygrid({url:'../treegrid/searchbox.json'});
	}else if (key=="window") {
		pgd.propertygrid({url:'../treegrid/window.json'});
	}else if (key=="dialog") {
		pgd.propertygrid({url:'../treegrid/dialog.json'});
	}
	pgd.propertygrid("loadData",[]);
}

function insert(){
	save();
	var obj = $('#tg') ;
	var arrRow = obj.treegrid("getRoots");
	var len = arrRow.length ;
	var data={id:new UUID().id,field:""} ;
	if(len==0){
		obj.treegrid("append",{data:[data]})	;
	}else{
		obj.treegrid("insert",{
			after : arrRow[len-1].id,
			data:data
		});
	}
	obj.treegrid("select",data['id']);
}

function generateHtml(){
	try{
		var treegrid = $("#tg") ;
		var arrRoot = treegrid.treegrid("getRoots");
		//var buffer = generate(arrRoot) ;
		var buffer = generateElt(arrRoot,treegrid) ;
		console.log(buffer);
		return buffer ;
	}catch(e){
		$.messager.alert('error',e);  
	}	
}

var rowNoCtrl = 4 ;
function generateElt(arrRoot,treegrid,parent){
	var buffer="" ;
	if(arrRoot){
		for(var index=0,len=arrRoot.length ;index<len ;index++){
			if(parent && arrRoot[index]._parentId!=parent.id){
					continue ;
			}
			if(parent && (parent['type']=='fieldset'||parent['type']=="table")){
				if(index%rowNoCtrl==0){
					buffer+="<tr>" ;
				}
				buffer+="<td>"+arrRoot[index]['name']+"</td><td>" ;
			}
			var children = treegrid.treegrid("getChildren",arrRoot[index].id) ;
			var tmpbuf = "" ;
			if(children && children.length>0){
				tmpbuf=generateElt(children,treegrid,arrRoot[index]);
			}
			var columns = treegrid.treegrid("getColumnFields") ;
			var strAttr = "" ;
			for (var pos=0 ,size=columns.length;pos<size;pos++){
				if("name"==columns[pos]){
					strAttr+=" title=\""+arrRoot[index][columns[pos]]+"\" " ;
				}else if(arrRoot[index][columns[pos]]){
					var fieldnm = columns[pos] ;
					if("options"==fieldnm){
						fieldnm="data-options";
						if(arrRoot[index][columns[pos]]){
							strAttr+=" "+fieldnm+"=\""+getDataOptions(JSON.parse(arrRoot[index][columns[pos]])) +"\"";
						}
					}else if("id"==fieldnm || "field"==fieldnm) {
						if("id"==fieldnm){
							strAttr+=" "+fieldnm+"=\""+arrRoot[index]['field'] +"\"";
						}else{
							continue ;
						}						
					}else {
						strAttr+=" "+fieldnm+"=\""+arrRoot[index][columns[pos]] +"\"";
					}						
				}
			}
			
			if(arrRoot[index]['type']=="column"){
				tmpbuf+=arrRoot[index]['name'];
			}
			
			buffer+=getSTag(arrRoot[index].type)+strAttr+(tmpbuf.length>0?(">"+getOtherAttr(arrRoot[index].type)+tmpbuf+getETag(arrRoot[index].type)):"/>")+"\r\n" ;
			if(parent && (parent['type']=='fieldset'||parent['type']=="table")){
				buffer+="</td>" ;
				if(((index+1)/rowNoCtrl>0 && (index+1)%rowNoCtrl==0)||index==len-1){
					buffer+="</tr>" ;
				}
			}
		}
	}
	return buffer ;
}

function getSTag(tagType){
	var strSTag = undefined ;
	switch (tagType) {
		case "combobox":
			 strSTag = "<select " ;
		break;
		case "datebox":
			 strSTag = "<input ";
		break;
		case "fieldset":
			 strSTag = "<fieldset ";
		break;
		case "table":
			 strSTag = "<table style=\"width:100%\" " ;
		break;
		case "datagrid":
			 strSTag = "<table ";
		break;
		case "column":
			 strSTag = "<th ";
		break;
		case "pagination":
			 strSTag = "<div ";
		break;
		case "tabs":
			 strSTag = "<div ";
		break;
		case "tab":
			 strSTag = "<div ";
		break;
		case "numberbox":
			 strSTag = "<input ";
		break;
		case "validatebox":
			 strSTag = "<input ";
		break;
		case "searchbox":
			 strSTag = "<input ";
		break;
		case "window":
			 strSTag = "<div ";
		break;
		case "dialog":
			 strSTag = "<div ";
		break;
		default:
			strSTag="" ;
	}
	return strSTag ;
}
function getETag(tagType){
	var strETag = undefined ;
	switch (tagType) {
		case "combobox":
			 strETag="</select>" ;
		break;
		case "datebox":
			 strETag = "</input> ";
		break;
		case "fieldset":
			 strETag = "</fieldset>";
		break;
		case "table":
			 strETag = "</tbody>\r\n</table>";
		break;
		case "datagrid":
			 strETag="</tr>\r\n</thead>\r\n</table>" ;
		break;
		case "column":
			 strETag="</th>" ;
		break;
		case "pagination":
			 strETag="</div>" ;
		break;
		case "tabs":
			 strETag="</div>";
		break;
		case "tab":
			 strETag="</div>";
		break;
		case "numberbox":
			 strETag="</input>";
		break;
		case "validatebox":
			 strETag="</input>";
		break;
		case "searchbox":
			 strETag="</input>";
		break;
		case "window":
			 strETag="</div>";
		break;
		case "dialog":
			 strETag="</div>";
		break;
		default:
			strETag="" ;
	}
	return strETag ;
}

function getOtherAttr(tagType){
	var str=undefined  ;
	switch (tagType) {
		case "datagrid":
			 str="<thead>\r\n<tr>";
		break;
		case "table":
			 str="<tbody>";
		break;
		default:
			str="" ;
	}
	return str ;
}

function getDataOptions(arrObj){
	var options = "" ;
	if(arrObj){
		for(var i=0,len=arrObj.length;i<len;i++){
			if (!arrObj[i].value|| !arrObj[i]['rowState'] || arrObj[i]['rowState']!='010') {
				continue ;
			}
			
			if(arrObj[i].name=="buttons"){
				options+=arrObj[i].name+":"+arrObj[i].value+"," ;
			}else if(arrObj[i].datatype=="string" || arrObj[i].datatype=="date" || arrObj[i].value=="auto"){
				options+=arrObj[i].name+":'"+arrObj[i].value+"'," ;
			}else{
				options+=arrObj[i].name+":"+arrObj[i].value+"," ;
			}
		}
		options = options.substring(0,options.length-1) ;
	}
	
	return options ;
}


function initaction(){
	$("#pgd").propertygrid({
		onClickRow:function(index,rowData){
			//var row = $(this).propertygrid("getSelected") ;
			if(!editingId){
				$.messager.alert('Warning','');
			}
			var arrEditor = $(this).propertygrid("getEditors",index) ;
			jQuery.each(arrEditor,function(index,editor){
				bindListener(editor,rowData) ;
			});
		}
		
	});
	
	$('#tt').tabs({   
	    border:false,   
	    onSelect:function(title){
	    	if(title=="preview"){
	    		document.getElementById("preDesigner").innerHTML=generateHtml();
		    	//document.getElementById("preDesigner").innerHTML="<table  id=\"aaa\" type=\"datagrid\" dataset=\"ds\" data-options=\"idField:'name'\"><thead><tr><th  id=\"bbbbb\" type=\"column\" dataset=\"ds\" data-options=\"title:'name',field:'name',width:60\"/></tr></thead></table>";  
		      //document.getElementById("preDesigner").innerHTML="<fieldset id=\"C5B877966D2000018224121B1E8C2D40\" type=\"fieldset\" dataset=\"ds\" data-options=\"\"><table style=\"width: 100%\" border=\"0\" cellpadding=\"2\"><tbody><tr><td>閹冨焼</td><td><select id=\"C5B8779772F00001B3D11E1C1BF01FA0\" type=\"combobox\" dataset=\"ds\" data-options=\"width:160,panelHeight:200,editable:true,disabled:false,hasDownArrow:'true',delay:200,valueField:'value',textField:'text',mode:'local'\"></select></td><td>閻㈢喐妫�/td><td><input id=\"C5B877DAC2600001F09D898B17C01E82\"  dataset=\"ds\" type=\"datebox\" data-options=\"fit:true,border:true,editable:false,hasDownArrow:true,delay:200,panelWidth:180,panelHeight:'auto',disabled:false\"></input></td><td>birthday</td><td><input id=\"C5B877DAC2600001F09D898B17C01E83\"  dataset=\"ds\" type=\"datebox\" data-options=\"fit:true,border:true,editable:false,hasDownArrow:true,delay:200,panelWidth:180,panelHeight:'auto',disabled:false\"></input></td><td>閸戣櫣鏁撻獮瀛樻箑</td><td><input id=\"C5B877DAC2600001F09D898B17C01E84\"  dataset=\"ds\" type=\"datebox\" data-options=\"fit:true,border:true,editable:false,hasDownArrow:true,delay:200,panelWidth:180,panelHeight:'auto',disabled:false\"></input></td></tr></tbody></table></fieldset>" ;  
		   		var elts = $(this).find("[dataset]");
		   		jQuery.each(elts,function(index,elt){
		   			var tmpid = "#"+elt.id ;
		   			if(elt.getAttribute("type")=="datebox" ){
		   				$(tmpid).datebox({});
		   			}else if(elt.getAttribute("type")=="combobox" ){
		   				$(tmpid).combobox({});
		   			}else if(elt.getAttribute("type")=="datagrid" ){
		   				$(tmpid).datagrid({});
		   			}else if(elt.getAttribute("type")=="pagination" ){
		   				$(tmpid).pagination({});
		   			}else if(elt.getAttribute("type")=="tabs" ){
		   				$(tmpid).tabs({});
		   			}else if(elt.getAttribute("type")=="numberbox" ){
		   				$(tmpid).numberbox({});
		   			}else if(elt.getAttribute("type")=="validatebox" ){
		   				$(tmpid).validatebox({});
		   			}else if(elt.getAttribute("type")=="searchbox" ){
		   				$(tmpid).searchbox({});
		   			}else if(elt.getAttribute("type")=="window" ){
		   				$(tmpid).window({});
		   			}else if(elt.getAttribute("type")=="dialog" ){
		   				$(tmpid).dialog({});
		   			}
		   		});
	    	} 
	    }   
	}); 
}


function bindListener(editor,rowData){
		var type = editor.type ;
		var target = $(editor.target) ;
		var field = editor.field ;
		if(type=="combobox"){
			var options = target.combobox("options") ;
			options.onSelect=function(record){
				setRecordValue(field,record.value,rowData);
				loadCtrlData(editor.field,record.value,rowData) ;
			} ;
			options.value=rowData[field] ;
			if(rowData['name']=="buttons"){
				target.combobox("loadData",buttons1);
			}
		}else if(type=="datebox"){
			
			var options = target.datebox("options") ;
			options.onSelect=function(date){
							var tmpVal = date.getFullYear() + "-"
							+ (date.getMonth() + 1) + "-"
							+ date.getDate();
			setRecordValue(field,tmpVal,rowData);
			} ;
		}else if(type=="validatebox"){
			target.validatebox("onBlur",function(val){
				setRecordValue(field,val,rowData);
			});
		}else if(type=="numberbox"){
			var options = target.numberbox("options") ;
			options.onChange=function(newVal,oldVal){
				setRecordValue(field,newVal,rowData);
			};
		}
}

function setRecordValue(field,newVal,rowData){
	//alert(rowData[field]+"--"+newVal)
	if(rowData[field]!=newVal){
		//010 表示数据已经被更改	rowData['rowState']='010' ;
	}
	rowData[field] = newVal ;
}

function contextAction(e, row) {
	e.preventDefault();
	$(this).treegrid('select', row['id']);
	$('#mm1').menu('show', {
		left : e.pageX,
		top : e.pageY
	});
}

function menuHandler(item){
	switch (item.name) {
		case "cut":
			 // statements
		break;
		case "append":
			 // statements
		break;
		case "copy":
			 // statements
		break;
		case "paste":
			 // statements
		break;
		default:
			$.messager.alert(item.text,"not find action...") ;
	}
	
}

function comboFilter(q, row){
	var opts = $(this).combobox('options');
	return row[opts.textField].indexOf(q) == 0;
}

function generateJsp(){
	var rows = $('#tg').treegrid("getData") ;
	$.ajax({
		
	});
}

$.extend($.fn.validatebox.methods, {
	getValue : function(jq) {
		return jq.each(function() {
			$(this);
		}).val();
	},
	onBlur : function(jq,caller){
		return jq.each(function(){
			$(this).bind("blur.validatebox",function(e){
					caller($(this).val());
				});
		});
	}  
});